package com.bsj.sipgateway.sip.session;

import com.bsj.sipgateway.sip.bean.VideoStreamSession;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.sip.Dialog;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author bsj-chenjunkang
 * @Description:视频流session管理器，管理视频预览、预览回放的通信句柄
 * @date 2022/8/31
 */
@Component
public class VideoStreamSessionManager {

    //播放视频session，key：deviceId_type(0：实时 1：历史,参考Constants常量)_channelSerial(逻辑通道号)
    private ConcurrentHashMap<String, VideoStreamSession> sessionMap = new ConcurrentHashMap<>();

    // deviceId:设备国标id channelSerial：设备逻辑通道号，不是实际通道号
    public VideoStreamSession putIfAbsent(String deviceId, String type, Dialog dialog, String ssrc, Integer port, String channelSerial) {
        VideoStreamSession videoStreamSession = new VideoStreamSession(dialog, ssrc, port);
        return sessionMap.putIfAbsent(deviceId + "_" + type + "_" + channelSerial, videoStreamSession);
    }

    public VideoStreamSession get(String deviceId, String type, String channelSerial) {
        return sessionMap.get(deviceId + "_" + type + "_" + channelSerial);
    }

    public boolean contain(String deviceId, String type, String channelSerial) {
        return sessionMap.containsKey(deviceId + "_" + type + "_" + channelSerial);
    }

    public void remove(String deviceId, String type, String channelSerial) {
        VideoStreamSession streamSession = sessionMap.get(deviceId + "_" + type + "_" + channelSerial);
        if (streamSession != null && StringUtils.isNotBlank(streamSession.getSsrc())) {
//            SsrcUtil.releaseSsrc(streamSession.getSsrc());
        }
        sessionMap.remove(deviceId + "_" + type + "_" + channelSerial);
    }

    public ConcurrentHashMap<String, VideoStreamSession> getAllMap() {
        return sessionMap;
    }
}
